﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using br.com.SistemaChamados;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Model;
using br.com.SistemaChamados.Enum;

public partial class Pages_CallSubCategoryInsert : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillDdlCategory();
        } 
    }
    private void FillDdlCategory()
    {
        CallCategoryController callCategoryController = new CallCategoryController();
        ddlCategory.DataSource = callCategoryController.GetCallCategories();
        ddlCategory.DataTextField = "Description";
        ddlCategory.DataValueField = "Id";
        ddlCategory.DataBind();
        ddlCategory.Items.Insert(0, "Selecione");
    }

    private void ClearFields()
    {
        txbSubCategory.Text = "";
        for (int i = 0; i < ddlCategory.Items.Count; i++)
        {
            ddlCategory.Items[i].Selected = false;
        }
        ddlCategory.Items[0].Selected = true;
    }

    protected void btnInsert_Click(object sender, EventArgs e)
    {
        CallSubCategory callSubCategory = new CallSubCategory();
        CallSubCategoryController callSubCategoryController = new CallSubCategoryController();
        CallCategory callCategory = new CallCategory();
        try
        {
            if (ddlCategory.SelectedIndex != 0)
            {
                callCategory.Id = Convert.ToInt32(ddlCategory.SelectedValue);
                callSubCategory.CallCategory = callCategory;
                callSubCategory.Description = Convert.ToString(txbSubCategory.Text);
                if (callSubCategoryController.InsertCallSubCategory(callSubCategory) == EnumGenericState.GENERIC_STATE_SUCCESS)
                {
                    Response.Write(@"<script language='javascript'>alert('Subcategoria cadastrada com sucesso!');</script>");
                    ClearFields();
                }
                else
                {
                    Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante o cadastro, por favor tente novamente!');</script>");
                }
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Selecione uma categoria.');</script>");
            }            
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao criar a subcategoria: <br>" + ex.Message + ".');</script>");
            callSubCategory = null;
            callSubCategoryController = null;
        }
    }
}